package com.zh.push.jpush;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 极光推送工具类
 * Created by linchaokun on 2018/7/5.
 */
@Component
@Lazy
public class JpushUtil {
    private static final Logger logger = LoggerFactory.getLogger(JpushUtil.class);

    @Autowired
    private JPushClient jpushClient;


    /**
     * 推送所有平台 用于广播消息  用于管理员使用
     *
     * @param responseNoticeMessage 消息
     */
    public void sendPushAllMessage(ResponseNoticeMessage responseNoticeMessage) {
        //生成推送的内容
        PushPayload payload = JPushClientPC.buildPushObject_all_message(responseNoticeMessage);
        sendPush(payload);
    }



    /**
     * 根据别名推送所有平台
     * 一次推送最多 1000 个。
     *
     * @param userNames             别名
     * @param responseNoticeMessage 消息
     */
    public void sendPushAliasAllMessage(List<String> userNames, ResponseNoticeMessage responseNoticeMessage) {
        //生成推送的内容
        PushPayload payload = JPushClientPC.buildPushObject_all_alias_message(userNames, responseNoticeMessage);
        sendPush(payload);
    }


    /**
     * 根据别名推送所有平台
     *
     * @param userName              别名
     * @param responseNoticeMessage 消息
     */
    public void sendPushAliasAllMessage(String userName, ResponseNoticeMessage responseNoticeMessage) {
        //生成推送的内容
        PushPayload payload = JPushClientPC.buildPushObject_all_alias_message(userName, responseNoticeMessage);
        sendPush(payload);
    }

    /**
     * 根据标签推送所有平台
     * 一次推送最多 20 个。
     *
     * @param tags                  标签名
     * @param responseNoticeMessage 消息
     */
    public void sendPushTagsAllMessage(List<String> tags, ResponseNoticeMessage responseNoticeMessage) {
        //生成推送的内容
        PushPayload payload = JPushClientPC.buildPushObject_all_tags_message(tags, responseNoticeMessage);
        sendPush(payload);
    }


    /**
     * 根据标签推送所有平台
     *
     * @param tag                   标签名
     * @param responseNoticeMessage 消息
     */
    public void sendPushTagsAllMessage(String tag, ResponseNoticeMessage responseNoticeMessage) {
        //生成推送的内容
        PushPayload payload = JPushClientPC.buildPushObject_all_tag_message(tag, responseNoticeMessage);
        sendPush(payload);
    }

    /**
     * 发送
     * @param payload
     * @return
     */
    private PushResult sendPush(PushPayload payload){
        try {
            PushResult result = jpushClient.sendPush(payload);
            jpushClient.close();

            return result;
        } catch (Exception e) {
            logger.info("sendPushAllAlert ： HTTP Status -=- {}", e.getMessage());

        }
        return null;
    }


}